// [1394]找出数组中的幸运数
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
    pub fn find_lucky(arr: Vec<i32>) -> i32 {
        let mut cnt_map = std::collections::HashMap::new();
        for x in arr {
            if let Some(cnt) = cnt_map.get_mut(&x) {
                // 修改需要解引用
                *cnt += 1;
            } else {
                cnt_map.insert(x, 1);
            }
        }
        cnt_map.iter().filter_map(|x| {
            if x.0 == x.1 {
                Some(*x.0)
            } else { None }
        }).max().unwrap_or(-1)
    }

    pub fn find_lucky2(arr: Vec<i32>) -> i32 {
        // rust中的getOrElseUpdate操作
        let mut cnt_map = std::collections::HashMap::new();
        for x in arr {
            *cnt_map.entry(x).or_insert(0) += 1;
            cnt_map.entry(x).and_modify(|x| *x += 1).or_insert(1);
        };
        cnt_map.iter().filter_map(|x| {
            if x.0 == x.1 {
                Some(*x.0)
            } else {
                None
            }
        }).max().unwrap_or(-1)
    }
}
//leetcode submit region end(Prohibit modification and deletion)


#[test]
fn main() {
    let arr = vec![2,2,3,4];
    assert_eq!(Solution::find_lucky2(arr), 2);
    let arr = vec![1,2,2,3,3,3];
    assert_eq!(Solution::find_lucky2(arr), 3);
    let arr = vec![2,2,2,3,3];
    assert_eq!(Solution::find_lucky2(arr), -1);
    let arr = vec![5];
    assert_eq!(Solution::find_lucky2(arr), -1);
    let arr = vec![7,7,7,7,7,7,7];
    assert_eq!(Solution::find_lucky2(arr), 7);
}